package ddz.db.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;

import java.util.List;
import java.util.Set;

public class AloneRedis extends AbsRedis implements IRedis {

    private int redisScanCount = 100;

    @Override
    public byte[] get(byte[] key) {
        if (key == null) {
            return null;
        }
        byte[] value;
        try (Jedis jedis = JedisFactory.getFactory().getJedis()) {
            value = jedis.get(key);
        }
        return value;
    }

    @Override
    public byte[] set(byte[] key, byte[] value, int expireTime) {
        if (key == null) {
            return null;
        }
        try (Jedis jedis = JedisFactory.getFactory().getJedis()) {
            jedis.setex(key, expireTime, value);
        }
        return value;
    }

    @Override
    public void del(byte[] key) {
        if (key == null) {
            return;
        }
        try (Jedis jedis = JedisFactory.getFactory().getJedis()) {
            jedis.del(key);
        }
    }

    @Override
    public Long dbSize(byte[] pattern) {
        long dbSize = 0L;
        JedisFactory factory = JedisFactory.getFactory();
        try (Jedis jedis = factory.getJedis()) {
            ScanParams params = new ScanParams();
            params.count(redisScanCount);
            params.match(pattern);
            byte[] cursor = ScanParams.SCAN_POINTER_START_BINARY;
            ScanResult<byte[]> scanResult;
            do {
                scanResult = jedis.scan(cursor, params);
                List<byte[]> results = scanResult.getResult();
                for (byte[] result : results) {
                    dbSize++;
                }
                cursor = scanResult.getCursorAsBytes();
            } while (scanResult.getStringCursor().compareTo(ScanParams.SCAN_POINTER_START) > 0);
        }
        return dbSize;
    }

    @Override
    public Set<byte[]> keys(byte[] pattern) {
        JedisFactory factory = JedisFactory.getFactory();
        try (Jedis jedis = factory.getJedis()) {
            return scanKeys(jedis, pattern);
        }
    }

    public int getRedisScanCount() {
        return redisScanCount;
    }

    public void setRedisScanCount(int redisScanCount) {
        this.redisScanCount = redisScanCount;
    }
}
